import java.util.Arrays;

public class TestHeap {
    public int[] elem;
    public int usedSize;
    public TestHeap(){
        this.elem=new int[10];
    }
    public void initHeap(int[] arr){
        for (int i = 0; i < arr.length; i++) {
            this.elem[i]=arr[i];
            this.usedSize++;
        }
    }
    public void createHeap(){
        //找到最后一棵子树的位置
        for ( int parent=(this.usedSize-1-1)/2; parent >= 0 ; parent--) {
            siftDown(parent,this.usedSize);
        }
    }
    //parent为起始位置
    //usedSize为判断结束的条件
    private void siftDown(int parent, int usedSize) {
        int child=2*parent+1;
        while (child<usedSize){
            //找左右子树的最大值
            if(child+1<usedSize&&elem[child]<elem[child+1]){
                child++;
            }
            //交换
            if(elem[parent]<elem[child]){
                swap(elem,parent,child);
                parent=child;
                child=2*parent+1;
            }else {
                break;
            }
        }
    }
    public void swap(int[] elem,int i,int j){
        int tmp=elem[i];
        elem[i]=elem[j];
        elem[j]=tmp;
    }
    public void push(int val){
        if(isFull()){
            elem= Arrays.copyOf(elem,elem.length*2);
        }
        elem[usedSize]=val;
        siftUp(usedSize);
        usedSize++;
    }

    private void siftUp(int child) {
        int parent=(child-1)/2;
        while (parent>=0){
            if(elem[child]>elem[parent]){
                swap(elem,child,parent);
                child=parent;
                parent=(child-1)/2;
            }else {
                break;
            }
        }
    }

    public boolean isFull(){
        return usedSize==elem.length;
    }
    public int poll(){
        if(isEmpty()){
            return -1;
        }
        int val = elem[0];
        swap(elem,0,usedSize-1);
        siftDown(0,usedSize-1);
        usedSize--;
        return val;
    }
    public boolean isEmpty(){
        return usedSize==0;
    }
    public int peek(){
        if(isEmpty()){
            return -1;
        }
        return elem[0];
    }
    public void heapSort(){

        int end = usedSize-1;
        while (end > 0) {
            swap(elem,0,end);
            siftDown(0,end);
            end--;
        }

    }
}
